#encoding:utf8
import os 
import shutil
import uuid
from lib.zippack import zip_dir
import uuid

class CocosUpload:
    
    def __init__(self, env):
        self._env = env


    @staticmethod
    def clear_cache(path, key):
        for f in os.listdir(path):
            t = os.path.join(path, f)
            if os.path.isdir(t) and \
                f.startswith(key):  
                shutil.rmtree(t)
 
    def zip(self, buildf):
        tag_key = "ziptemp@"
        tmp_key = str(uuid.uuid4())

        p_tar = os.path.join(os.getcwd(),tag_key + tmp_key)
        if os.path.isdir(p_tar):
            shutil.rmtree(p_tar)
        os.mkdir(p_tar)
        self.copy_pack(buildf, p_tar)
        zip_dir(p_tar, "%s.zip"%tmp_key)


    def copy_pack(self, buildf, tarf):
        f1 = os.path.join(self._env.hotpub_dir, "project.manifest")
        f2 = os.path.join(self._env.hotpub_dir, "version.manifest")

        t1 = os.path.join(tarf, "project.manifest")
        t2 = os.path.join(tarf, "version.manifest")
        
        d1 = os.path.join(buildf, "assets")
        d2 = os.path.join(buildf, "src")

        dt1 = os.path.join(tarf, "assets")
        dt2 = os.path.join(tarf, "src")
        shutil.copyfile(f1, t1)
        shutil.copyfile(f2, t2)
        if os.path.isdir(dt1):
            shutil.rmtree(dt1)
        shutil.copytree(d1, dt1)
        if os.path.isdir(dt2):
            shutil.rmtree(dt2)
        shutil.copytree(d2, dt2) 
        


    def upload_to_sftp(self, **kwads):
        host = kwads.get('host', 'localhost')
        usr = kwads.get("usr", "dwb")
        pwd = kwads.get("pwd", "asdf")
        